package com.example.rbacmanage.service.system.impl;

import com.example.rbacmanage.common.enums.UploadTypeEnum;
import com.example.rbacmanage.property.DefinedProperty;
import com.example.rbacmanage.service.system.UploadFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.Date;

@Service
public class UploadFileServiceImpl implements UploadFileService {
    @Autowired
    private DefinedProperty definedProperty;
    @Override
    public String uploadFile(String type, MultipartFile file) {
        if (UploadTypeEnum.LOCALUPLOAD.getType().equals(type.trim())){
            LocalDate currentDate = LocalDate.now();
            String dateDir = definedProperty.getUploadProfile() + String.format("%s/%s/%s",currentDate.getYear(),currentDate.getMonthValue(),currentDate.getDayOfMonth());
            Path dirPath = Paths.get(dateDir);
            if (!Files.exists(dirPath)){
                try {
                    Files.createDirectories(dirPath);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            String fileName = dateDir.concat("/") +System.currentTimeMillis()+file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));
            Path path = Paths.get(fileName);
            try {
                Files.copy(file.getInputStream(),path);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return fileName.replace(definedProperty.getUploadProfile(), "/profile/");
        }
        return null;
    }
}
